import { createApp, watch } from 'vue'
import { createPinia } from 'pinia'
import plugins from '@/plugins'
import App from './App.vue'
import router from './router'
import ElementPlus from 'element-plus'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import 'normalize.css'
import '@/style/scroll.scss'
import '@/style/global.scss'
import '@/style/el.scss'
import '@/style/admin.scss'
import adminComponent from './components/index'
import adminUtils from './utils/index'
import directive from './directive/index.js'
import 'vant/lib/index.css'
import { Notify } from 'vant'
import { pinia } from './stores'
import { useDark } from '@vueuse/core'
import { useSystemStore } from '@/stores'
import packageJson from '@/../package.json'
import { isMobile } from '@/utils/index'
import '@/style/pagination-fix.scss';

// 只在移动端启用flexible
if (isMobile()) {
  import('amfe-flexible').then((module) => module.initRem())
}

const app = createApp(App)
app.config.globalProperties.$env = import.meta.env
app.use(createPinia())
app.use(directive)
app.use(plugins)
app.use(ElementPlus, {
  locale: zhCn
})
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}
app.use(adminUtils)
app.use(adminComponent)

// 注册 Vant Notify 组件
app.use(Notify)

app.use(router)

const isDark = useDark()

// 监听主题变化，动态调整某些组件
const handleThemeChange = () => {
  // 设置HTML文档的data-theme属性，便于CSS选择器使用
  document.documentElement.setAttribute('data-theme', isDark.value ? 'dark' : 'light')

  // 触发自定义事件，便于组件监听主题变化
  window.dispatchEvent(new CustomEvent('theme-change', { detail: { isDark: isDark.value } }))
}

// 初始化时执行一次
handleThemeChange()

// 监听主题变化
watch(isDark, () => {
  handleThemeChange()
})

// 将isDark添加到app全局属性中，便于组件访问
app.config.globalProperties.$isDark = isDark

app.mount('#app')

// 在main.js中设置动态标题
document.title = import.meta.env.VITE_APP_TITLE
